# coding: utf-8

from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from flask_principal import Permission, RoleNeed
from flask_login import LoginManager
from book.forms import BookAddForm, BookEditForm
from db.models import db, User, Book
from permission_control import permission_required
from const import PERMISSION, BorrowCardApplyStatus
from config import app

book_blueprint = Blueprint('book_manage', __name__)


@book_blueprint.route('/book_manage/list', methods=['GET'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_VIEW.KEY)
def book_list():
    books = Book.query.filter_by(is_delete=0).all()
    return render_template('book_manage/books.html', books=books, username=current_user.username)


@book_blueprint.route('/book_manage/add', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_ADD.KEY)
def book_add():
    form = BookAddForm()
    if form.validate_on_submit():
        existing_book = Book.query.filter_by(
            name=form.name.data, 
            author=form.author.data, 
            is_delete=0).first()
        if existing_book is None:
            book = Book(name=form.name.data)
            book.book_type_id = form.book_type_id.data
            book.author = form.author.data
            book.price = form.price.data
            book.is_active = bool(form.is_active.data)
            db.session.add(book)
            db.session.commit()
            flash('添加成功！', 'success')
            return redirect(url_for('book.book_list'))
        flash(f'由{form.author.data}编写的{form.name.data}这本书已被添加，请尝试添加其他书籍。', 'danger')
    return render_template('book_manage/book_add.html', form=form)


@book_blueprint.route('/book_manage/edit/<int:book_id>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_EDIT.KEY)
def book_edit(book_id):
    book = Book.query.filter_by(id=book_id).first()
    if not book:
        flash('没有找到要编辑的书籍。', 'danger')
        return redirect(url_for('book.book_list'))
    form = BookEditForm(obj=book)
    if form.validate_on_submit():
        form.populate_obj(book)
        db.session.commit()
        flash('书籍信息已更新！', 'success')
        return redirect(url_for('book.book_list'))
    return render_template('book_manage/book_edit.html', book=book, form=form)


@book_blueprint.route('/book_manage/delete/<int:book_id>', methods=['GET', 'POST'])
@login_required
@permission_required(PERMISSION.PERM_BOOK_DELETE.KEY)
def book_delete(book_id):
    book = Book.query.filter_by(id=book_id).first()
    book.is_delete = 1
    db.session.commit()
    flash('书籍信息已删除！', 'success')
    return redirect(url_for('book_manage.book_list'))
